<template>
  <!--电量平衡分析-->
  <d2-container>
  <section class="vue-wrap2">
    <el-row style="padding:0px 20px 6px; ">
      <el-col :span="24" style="margin-top: 15px">
        <el-col :span="8">
          <span style="font-size: 14px;"class="theme-front-color">电量平衡 :</span>
       <!--   <el-radio v-model="powBalance" label="2" class="label_obj" @change.native="showvalue()">变压器电量平衡</el-radio>-->
         <el-radio v-model="powBalance" label="1" class="label_obj" @change.native="showvalue()">母线电量平衡</el-radio>
        </el-col>
        <el-col :span="12">
          <span style="font-size: 14px;margin-right: 5px"class="theme-front-color">选择时间 :</span>
          <label name="按日" class="label_time_a" v-bind:class="{ active: timeType==='1', 'checked': timeType==='1' }"
                 v-on:click="changeTimeType('1')">按日</label>
          <label name="按月" class="label_time_b" v-bind:class="{ active: timeType==='2', 'checked': timeType==='2' }"
                 v-on:click="changeTimeType('2')">按月</label>
          <label style="margin-left: 30px;">
          <span class="search-input" v-show="timeType == 1">
            <el-date-picker
              type="date"
              size="mini"
              v-model="dateTime"
              :picker-options="pickerOptions1"
              placeholder="选择日期"
            ></el-date-picker>
          </span>
          <span class="search-input" v-show="timeType == 2">
            <el-date-picker
              type="month"
              size="mini"
              format="yyyy年MM月"
              v-model="monthTime"
              :picker-options="pickerOptions1"
              placeholder="选择月份"
            ></el-date-picker>
          </span>
          </label>
        </el-col>

        <el-col :span="4" style="text-align: right;">
          <el-button @click="getList(true)" size="mini" type="info"
                     style="width: 80px;border-radius: 0;background: #4d87df;
                        border: 1px solid #4d87df;border-radius: 5px">查询
          </el-button>
        </el-col>
      </el-col>
      <el-col :span="24" style="margin-top: 15px">
        <div class="clearfloat" style="width:100%;height:auto;overflow:hidden">
          <div style="font-size: 14px;margin-top:10px;"class="theme-front-color">选择对象 :</div>
          <div v-show="objlist.length>0" style="margin-left: 80px;margin-top: -25px;width: 90%;word-wrap:break-word; overflow:hidden;">
            <el-radio-group v-model="selectObj" text-color="#333333" fill="#83acf9"
                            style="font-size: 14px;">
              <template v-for="(item,index) in objlist">
                <el-radio-button :label="item.meterCode" :key="index" style="display: none" :name="item.deviceName"
                                 @change.native="changeObjvalue(item)"
                                 border>
                </el-radio-button>
                <label :name="item.meterCode" :key="item.meterCode" class="label_obj" :for="item.deviceName"
                       v-bind:class="{ active: selectObj===item.meterCode, 'checked': selectObj===item.meterCode }"
                       v-on:click="changeObjvalue(item)">{{item.deviceName}}</label>
              </template>
            </el-radio-group>
          </div>
        </div>


      </el-col>
    </el-row>
    <el-row style="padding:20px 0px 26px 20px;">
      <el-col :span="24" class="monitor-d">

        <div class="power-statistics" style="border-top: 1px dashed #DADADA;"  v-loading="dayEchartData === '2'" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading">
          <div class="chart-head clearfloat">
            <span class="tit theme-front-color">电量平衡趋势</span>
          </div>
          <div class="statistics-d">
            <div class="note" v-show="dayEchartData === '0'" style="width: 100%">
              <img src="../../assets/img/noechart.png" class="m-auto">
              <p>暂无相关数据</p>
            </div>
            <div id="statEchart1" style="width: 100%">
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row style="padding:20px 20px 26px; ">
      <el-col :span="24">
        <div class="vue-body">
          <div class="chart-head clearfloat">
            <span class="tit theme-front-color">电量平衡表</span>
          </div>


          <el-table :data="query.list.slice((query.page_no-1)*query.page_size,query.page_no*query.page_size)"  class="chart-head" tooltip-effect="dark" style="width: 100%;
       " border>
            <el-table-column prop="time" label="时间" min-width="120" align="center" :formatter="showDisplayTimeName">
            </el-table-column>
            <el-table-column prop="p_val" :label="objName+'（kWh）'" min-width="120" align="center">
              <template slot-scope="scope">
                {{(scope.row.p_val).toFixed(1)}}
              </template>
            </el-table-column>
            <el-table-column prop="ch_val" label="所属下级（kWh）" min-width="120" align="center">
              <template slot-scope="scope">
                {{(scope.row.ch_val).toFixed(1)}}
              </template>
            </el-table-column>
            <el-table-column prop="ch_val" label="电量差值（kWh）" min-width="120" align="center">
              <template slot-scope="scope">
                {{(scope.row.p_val - scope.row.ch_val).toFixed(1)}}
              </template>
            </el-table-column>
            <el-table-column prop="pro" label="不平衡度（%）" min-width="100" align="center">
              <template slot-scope="scope">
                {{(scope.row.pro * 100).toFixed(1) + '%'}}
              </template>
            </el-table-column>
            <el-table-column prop="pro" label="状态" show-overflow-tooltip min-width="100" align="center"
                             :filters="[{text: '超标', value: '超标'}, {text: '正常', value: '正常'}]"
                             :filter-method="filterValue" filter-placement="bottom-end">
              <template slot-scope="scope">
                <img src="../../assets/img/lower.png" v-if="formatObjvalue(scope.row)==='正常'">
                <img src="../../assets/img/higher.png" v-if="formatObjvalue(scope.row)==='超标'">
                {{ formatObjvalue(scope.row)}}
              </template>
            </el-table-column>
          </el-table>
          <template>
            <pagintation :total="query.total" :props_page_sizes="query.page_size" @changeCurrent="changeVal" @changeSize="changeSize"></pagintation>
          </template>
          <!--<dialog></dialog>-->
        </div>
      </el-col>
    </el-row>
  </section>
  </d2-container>
</template>

<script>
  import * as Util from "@/utils";
  import Config from "@/utils/config"
  import commondef from '@/utils/common'
  import pagintation from '@/components/pagintation/index.vue'
  //  import cityList from '../../../api/vueCity'
  import * as echarts from 'echarts'

  export default {
    data () {
      return {
        customer_id: this.$store.state.customer_id,
        dayEchartData: '0',
        objlist: [],
        selobj: '',
        powBalance: '1',
        balancStander: '',
        balancStanderName: '下',
        selectObj: '',
        objName: '',
        timeType: '1',
        setUp: false,
        dateTime: new Date(new Date().getTime()),
        monthTime: new Date(),
        pickerOptions1: {
          disabledDate (time) {
            return time.getTime() > (new Date().getTime())
          }
        },
        menuTree: {
          defaultProps: {
            children: 'children',
            label: 'name'
          },
          data: []
        },
        customerName: this.$store.state.customer_domain_name,
        customer_id: this.$store.state.customer_id,
        show: 'tab',
        query: {
          page_no: 1,
          page_size: 15,
          total: 0,
          list: []
        },
        roleOptions: [],
        editForm: {
          id: '',
          data: {
            customer_domain_name: '',
            role_name: '',
            role_id: '',
            info: {
              home: []
            }
          },
          show: false,
          status: false,
          title: '',
          rules: {
            role_name: [
              {required: true, message: '请输入⻆⾊名称', trigger: 'blur'},
              {max: 30, message: '不能超过 30 个字符', trigger: 'blur'}
            ]
          }
        },
        dayOptin: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'],
        monthOption: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'],
        optionfad: {
          grid: {
            left: 30,
            top: 40,
            right: 50,
            bottom: 40
          },
          color: ['#708DE5', '#2BD597', '#F5A623'],
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function (val, n) {
              var returnStr = '<div style=\'text-align:left;\'>' +
                '时间：' + val[0].name + '<br/>'
              for (var i in val) {
                returnStr = returnStr +
                  '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + val[i].color + '\'></span>' +
                  val[i].seriesName + '：' + val[i].value + (val[i].seriesName === '纯电量费用' ? ' 元' : ' 元/kWh') +
                  '<br/>'
              }
              returnStr = returnStr + '</div>'
              return returnStr
            }
          },
          legend: {
            x: 'right',
            padding: [15, 50, ,],
            itemWidth: 10,
            itemHeight: 10,
            textStyle: {
              color: '#ffffff' // 设置图例文字颜色为白色
            },
            data: [{
              name: '有功电量',
              icon: 'circle'
            }, {
              name: '下属线路有功电量',
              icon: 'circle'
            }, {
              name: '不平衡度',
              icon: 'circle'
            }],
          },
          xAxis: [
            {
              type: 'category',
              boundaryGap: true,
              data: []
            },
            {
              type: 'category',
              boundaryGap: true,
              show: false,
              data: []
            }
          ],
          yAxis: [
            {
              type: 'value',
              scale: true,
              splitNumber: 6,
              name: '单位  kWh',
              boundaryGap: [0.2, 0.2],
              splitLine:{
                show : true
              },
              axisLabel: {
                formatter: function (a) {
                  return a >= 1000
                    ? echarts.format.addCommas(a / 1000) + 'k'
                    : a
                }
              }
            },
            {
              type: 'value',
              scale: true,
              splitNumber: 6,
              axisLabel: {
                formatter: function (a) {
                  return (a) + '%'
                }
              },
              boundaryGap: [0.2, 0.2],
              splitLine:{
                show : false
              }
            }
          ],
          series: [
            {
              name: '有功电量',
              type: 'bar',
              barGap: '30%',
              barWidth: '30%',
              barCategoryGap: '70%',
              itemStyle: {
                //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
                emphasis: {
                  barBorderRadius: 30,
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(112,141,229, 0.5)'
                },
                normal: {
                  //柱形图圆角，初始化效果
                  barBorderRadius: 10
                }
              },
              data: []
            },
            {
              name: '下属线路有功电量',
              type: 'bar',
              barGap: '30%',
              barWidth: '30%',
              barCategoryGap: '70%',
              itemStyle: {
                //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
                emphasis: {
                  barBorderRadius: 30,
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(112,141,229, 0.5)'
                },
                normal: {
                  //柱形图圆角，初始化效果
                  barBorderRadius: 10
                }
              },
              data: []
            },
            {
              name: '不平衡度',
              type: 'line',
              yAxisIndex: 1,
              data: []
            }
          ]
        }
      }
    },
    methods: {
      changeTimeType (value) {
        this.timeType = value
      },
      objOnclick (item) {
        var labels = document.getElementById('selectObj').getElementsByTagName('label')
        var radios = document.getElementById('selectObj').getElementsByTagName('input')
        var obj = document.getElementsByName(item.tree_id)
        if (obj[0].className == '') {
          for (var k = 0, l = labels.length; k < l; k++) {
            labels[k].className = ''
            radios[k].checked = false
          }
          obj[0].className = 'checked'
          var obj1 = document.getElementById(item.info.name)
          obj1.checked = true
          this.changeObjvalue(item)
        }
      },
      filterValue (value, row, column) {
        return this.formatObjvalue(row) === value
      },
      changeObjvalue (item) {
        this.selectObj = item.meterCode
        this.objName = item.deviceName
        if (this.powBalance === '1') {
/*          var eddyb = item.info.leave.toUpperCase()
          if (eddyb === '1-10KV') {
            this.balancStander = '±5%'
            this.balancStanderName = '下'
          } else {
            this.balancStander = '±2%'
            this.balancStanderName = '上'
          }*/
        } else if (this.powBalance === '2')
          var eddyb = item.base_info.base_info.eddyb.split('/')
        if (parseFloat(eddyb[0] / eddyb[1]) <= parseFloat(10.5 / 0.4)) {
          this.balancStander = '±5%'
          this.balancStanderName = '下'
        } else {
          this.balancStander = '±2%'
          this.balancStanderName = '上'
        }
      },
      formatObjvalue (item) {
        var balancStander = ''
        var eddyb = item.pro * 100
        var standar = 0
        if (this.balancStander === '±5%') {
          standar = 5
        } else if (this.balancStander === '±2%') {
          standar = 2
        }
        if (eddyb <= standar && eddyb >= -standar) {
          balancStander = '正常'
        } else {
          balancStander = '超标'
        }
        return balancStander
      },
      showvalue (flag) {

        this.$api.okhttp({
          url: this.$http.adornUrl('/ecs/ecsmeterinfo/getMeterList'),
          method: 'get',
          params: this.$http.adornParams({
            'projectId': this.$util.cookies.get("cuuren_projectId"),
            "customerId":this.$util.cookies.get('customer_id')
          })
        }).then((data) => {
          if (data && data.code === 0) {
          this.objlist = data.data
          if(this.objlist.length>0) {
            this.selectObj = data.data[0].meterCode;
            if (flag) {
              this.getList();
            }
          }
        }
      });

      },
      showDisplayName (row, column, cellValue) {
//        console.log(cellValue)
        return '<img src=\"../../assets/img/lower.png\">' + cellValue
      },
      changeVal (val) {
        this.query.page_no = val
//        this.getList()
      },
      changeSize (val) {
        this.query.page_size = val
//        this.getList()
      },
      renderContent: function (createElement, {node, data, store}) {
        return createElement('span', {
          attrs: {
            style: 'display:inline-block; position: relative;width: 100%'
          }
        }, [
          createElement('span', node.label),
          createElement('span', {
            attrs: {
              style: 'position: absolute; right: 100px'
            }
          })
        ])
      },
      getList () {
        this.query.page_no =1;
        let myChart2 = echarts.init(document.getElementById('statEchart1'))
        myChart2.clear()
        this.dayEchartData = '2'
        this.query.list = []
        function getLastDay (year, month) {
          let newYear = year  //  取当前的年份
          let newMonth = month  // 取下一个月的第一天，方便计算（最后一天不固定）
          let newDate = new Date(newYear, newMonth, 1)        //  取当年当月中的第一天
          return new Date(newDate.getTime() - 1000 * 60 * 60 * 24)
        }
        function compare (obj1, obj2) {
          var val1 = obj1.time
          var val2 = obj2.time
          if (val1 < val2) {
            return -1
          } else if (val1 > val2) {
            return 1
          } else {
            return 0
          }
        }
        let strTime = new Date(this.dateTime).format('yyyy-MM-dd')
        let endTime = new Date(this.dateTime).format('yyyy-MM-dd')
        if (this.timeType === '2') {
          strTime = new Date(this.monthTime.getFullYear(), this.monthTime.getMonth(), 1).format('yyyy-MM-dd')
          endTime = getLastDay(this.monthTime.getFullYear(), (this.monthTime.getMonth() + 1)).format('yyyy-MM-dd')
        }
        var para = {
          customerId: this.$util.cookies.get("customer_id"),
          meterCode: this.selectObj,
          startTime: strTime,
          endTime: endTime,
          type: this.timeType === '1' ? 'day' : 'month'
        }
//        console.log('para', para)
        this.$api.okhttp({
          url: this.$http.adornUrl('/eda/datavincent.dist_power.get_electricity'),
          method: 'post',
          data: this.$http.adornParams(para)
        }).then(res => {
            if (res.code === 0) {
              if(res.data.length>0) {
                var dataAll = res.data.sort(compare)
                this.query.list = dataAll
                this.query.total = res.data.length
                this.getbar(dataAll)
              }else{
                this.dayEchartData = '0'
              }
            }else{
              this.dayEchartData = '0'
            }
          })
      },
      monthTimefun (val) {
        var returnStr = '<div style=\'text-align:left;\'>' +
          '时间：' + (new Date(this.monthTime.getFullYear(), this.monthTime.getMonth(), val[0].name).format('yyyy-MM-dd')) + '<br/>'
        for (var i in val) {
          returnStr = returnStr +
            '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + val[i].color + '\'></span>' +
            val[i].seriesName.replace('有功电量', '') + '：' + val[i].value + (val[i].seriesName === '不平衡度' ? ' %' : ' kWh') +
            '<br/>'
        }
        returnStr = returnStr + '</div>'
        return returnStr
      },
      getbar (data) {
        var that = this
        //设置数组
        var data1 = []
        var data2 = []
        var data3 = []
        var dlmin = 0
        var dlmax = 0
        var phmin = 0
        var phmax = 0
        if (data.length > 0) {

          that.dayEchartData = '1'
          var dataAll = data//所有
          var options = {}
          var k = 0
          var xaislength = that.timeType === '1' ? 24 : 32
          for (var i = 0; i < xaislength; i++) {
            if (k < dataAll.length) {
              var day = that.timeType === '1' ? (new Date(dataAll[k].time).format('hh')) : (new Date(dataAll[k].time).format('dd'))
              if (i === (parseInt(day) - (that.timeType === '1' ? 0 : 1))) {
                data1.push(dataAll[k].p_val.toFixed(1))
                data2.push(dataAll[k].ch_val.toFixed(1))
                data3.push((dataAll[k].pro * 100).toFixed(1))
                if(parseFloat(dataAll[k].p_val.toFixed(1))>=dlmax){
                  dlmax = parseFloat(dataAll[k].p_val.toFixed(1))
                }
                if(parseFloat(dataAll[k].ch_val.toFixed(1))>=dlmax){
                  dlmax = parseFloat(dataAll[k].ch_val.toFixed(1))
                }
                if(parseFloat((dataAll[k].pro * 100).toFixed(1)) >= phmax){
                  phmax = parseFloat((dataAll[k].pro * 100).toFixed(1))
                }
                if(parseFloat((dataAll[k].pro * 100).toFixed(1))<=phmin){
                  phmin = parseFloat((dataAll[k].pro * 100).toFixed(1))
                }

                k++
              } else {
                data1.push('')
                data2.push('')
                data3.push('')
              }
            }
          }
        } else {
          return false
        }
        function getLastDay (year, month) {
          let newYear = year  //  取当前的年份
          let newMonth = month  // 取下一个月的第一天，方便计算（最后一天不固定）
          let newDate = new Date(newYear, newMonth, 1)        //  取当年当月中的第一天
          return new Date(newDate.getTime() - 1000 * 60 * 60 * 24)
        }
        //获取横坐标长度
        var monthtooltips = {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (val, n) {
            var returnStr = '<div style=\'text-align:left;\'>' +
              '时间：' + val[0].name + '日<br/>'
            return that.monthTimefun(val)
          }
        }
        var daytooltips = {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (val, n) {
            var returnStr = '<div style=\'text-align:left;\'>' +
              '时间：' + val[0].name + ':00<br/>'
            for (var i in val) {
              returnStr = returnStr +
                '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + val[i].color + '\'></span>' +
                val[i].seriesName.replace('有功电量', '') + '：' + val[i].value + (val[i].seriesName === '不平衡度' ? ' %' : ' kWh') +
                '<br/>'
            }
            returnStr = returnStr + '</div>'
            return returnStr
          }
        }
        var optionsfand = that.optionfad
        optionsfand.series[0].name = that.objName + '有功电量'
        optionsfand.legend.data[0].name = that.objName + '有功电量'
        optionsfand.tooltip = that.timeType === '1' ? daytooltips : monthtooltips
        var xAxisData = that.timeType === '1' ? that.dayOptin : that.monthOption
        optionsfand.xAxis[0].data = xAxisData.slice(0, that.timeType === '1' ? 24 : parseInt(getLastDay(that.monthTime.getFullYear(), (that.monthTime.getMonth() + 1)).format('dd')))

        var ylen = parseInt(String(parseInt(dlmax)).length)
        optionsfand.yAxis[0].min = 0
        optionsfand.yAxis[0].max = (Math.ceil(dlmax/(3*Math.pow(10,ylen-1))))*3*Math.pow(10,ylen-1)
        var maxNum = Math.abs(phmax)
        var minNum = 0
        if(Math.abs(phmin)>Math.abs(phmax)){
          maxNum = Math.abs(phmin)
        }

        if(phmax<0||phmin>0){
          maxNum = Math.ceil(maxNum/6)*6
          if(phmax<0){
            minNum = -maxNum
            maxNum = 0
          }
        }else{
          maxNum = Math.ceil(maxNum/3)*3
          minNum = -maxNum
        }

        optionsfand.yAxis[1].min = minNum
        optionsfand.yAxis[1].max = maxNum
        optionsfand.series[0].data = data1
        optionsfand.series[1].data = data2
        optionsfand.series[2].data = data3
        setTimeout(function () {
          //画电费电量图
          let myChart2 = echarts.init(document.getElementById('statEchart1'))
          myChart2.clear()
          myChart2.setOption(optionsfand)
        }, 500)
      },
      showDisplayTimeName(row, column, cellValue) {
       // return this.timeType==='1'? (new Date(cellValue).format('yyyy-MM-dd hh:mm')):cellValue
        return cellValue;
      }
    },
    mounted () {
      this.showvalue(1)
//      this.getList()
    },
    components: {
      pagintation
    }
  }
</script>

<style scoped lang="scss">
  @import "../../assets/scss/_variables";
  .top-but-box.el-col.el-col-2 {
    margin-right: 20px;
  }

  .el-input.el-input--small {
    width: 205px;
  }

  .chart-head {
    margin-top: 10px;
  }

  .clearfloat:after {
    display: block;
    clear: both;
    content: "";
    visibility: hidden;
    height: 0
  }

  .clearfloat {
    zoom: 1
  }

  .power-statistics {
    /*padding: 5px 5px 10px 15px;*/
    height: 290px;
  /* background: $font-white;*/
   width: 100%;
 }

 .note {
   padding: 20px;
   text-align: center;
   color: #666;
 }

 .note img {
   width: 140px;
 }

 .statistics-d > div {
   height: 300px;
   width: 100%;
 }

 .label_obj {
   font-family: MicrosoftYaHei;
   display: -moz-inline-block;
   display: inline-block;
   cursor: pointer;
   margin: 0 10px;
   line-height: 30px;
   background: none;
   padding: 1px 10px;
   border-radius: 4px;
   border: 1px solid #fff;
   font-size: 14px;
   color: #666666;
 }

 .label_time_a {
   font-family: MicrosoftYaHei;
   display: -moz-inline-block;
   display: inline-block;
   cursor: pointer;
   line-height: 24px;
   background: none;
   padding: 1px 10px;
   border-radius: 4px 0 0 4px;
   border-top: 1px solid #678AF4;
   border-left: 1px solid #678AF4;
   border-bottom: 1px solid #678AF4;
   font-size: 14px;
   color: #666666;
   margin-left: 18px;
 }

 .label_time_b {
   font-family: MicrosoftYaHei;
   display: -moz-inline-block;
   display: inline-block;
   cursor: pointer;
   line-height: 24px;
   background: none;
   padding: 1px 10px;
   border-radius: 0px 4px 4px 0px;
   border-top: 1px solid #678AF4;
   border-right: 1px solid #678AF4;
   border-bottom: 1px solid #678AF4;
   font-size: 14px;
   color: #666666;
   margin-left: 1px;
 }

 label.checked {
   border: 2px solid #666666;
   color: #666666;
 }
</style>

